package com.web.portal.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.web.portal.pojo.FacultyPojo;
import com.web.portal.service.FacultyService;

@Component
public class AddFacultyValidor implements Validator {
	@Autowired
	FacultyService facultyService;

	public FacultyService getFacultyService() {
		return facultyService;
	}

	public void setFacultyService(FacultyService facultyService) {
		this.facultyService = facultyService;
	}

	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return FacultyPojo.class.isAssignableFrom(clazz);
	}

	public void validate(Object faculty, Errors error) {
		// TODO Auto-generated method stub
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "firstName",
				"required.firstName", "Please provide valid name");
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "lastName",
				"required.lastName", "Please provide valid last name");
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "mail",
				"required.mail", "Please provide valid email");

		FacultyPojo facultyPojo = (FacultyPojo) faculty;
		if (!(facultyPojo.getPhone().trim().length() == 10)) {
			error.rejectValue("phone", "notmatch.phone",
					"Enter ten digits phone number without space");
		}
		if (facultyPojo.getMyFileImage().getBytes().length > 8388608
				|| facultyPojo.getMyFileMap().getBytes().length > 8388608) {
			error.rejectValue("myFileMap", "notmatch.myFileMap",
					"File size must be less than 4 MB");
		}
		if (!error.hasErrors()) {
			if (facultyService.isAddedAlready(facultyPojo.getMail())) {
				error.rejectValue("mail", "duplicate.mail",
						"Faculty under that email is already registered");
			}
		}
	}

}
